using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace TraceMonitor
{
    public partial class frmMain : Form
    {
        [DllImport("User32.dll", CharSet = CharSet.Auto, EntryPoint = "SendMessage")]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        private delegate void SetText(string strMsg);

        private System.Net.Sockets.TcpClient m_objTcpClient = null;

        private System.Threading.Thread m_tTrace = null;

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            tstxtIpAddress.Text = Program.GetConfig(Program.CONFIG_IPADDRESS);
            tstxtPort.Text = Program.GetConfig(Program.CONFIG_PORT);
        }

        private void SetTrace(string strMsg)
        {
            if (txtMsg.InvokeRequired)
            {
                SetText objSetText = new SetText(SetTrace);
                this.Invoke(objSetText, new object[] { strMsg });
            }
            else
            {
                txtMsg.Text += strMsg + Environment.NewLine;
                if (tsbtnAutoScroll.Checked)
                    ScrollTrace();
            }
        }

        private void ScrollTrace()
        {
            const int WM_VSCROLL = 277;
            const int SB_BOTTOM = 7;

            IntPtr ptrWparam = new IntPtr(SB_BOTTOM);
            IntPtr ptrLparam = new IntPtr(0);
            SendMessage(txtMsg.Handle, WM_VSCROLL, ptrWparam, ptrLparam);
        }

        private void ReadTrace()
        {
            try
            {
                while (m_objTcpClient != null && m_objTcpClient.Connected)
                {
                    System.Net.Sockets.NetworkStream objNetworkStream = m_objTcpClient.GetStream();
                    if (objNetworkStream == null)
                        break;

                    System.IO.StreamReader sr = new System.IO.StreamReader(objNetworkStream);
                    if (sr == null)
                        break;

                    string strMsg = sr.ReadLine();
                    if (!strMsg.Equals(string.Empty))
                        SetTrace(strMsg);
                }
            }
            catch { }
        }

        private void txtMsg_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }

        private void tsbtnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                string strIpAddress = tstxtIpAddress.Text;
                string strPort = tstxtPort.Text;

                if (strIpAddress == null || strPort == null || strIpAddress.Equals(string.Empty) || strPort.Equals(string.Empty))
                    return;

                m_objTcpClient = new System.Net.Sockets.TcpClient(strIpAddress, Convert.ToInt32(strPort));
                if (m_objTcpClient == null)
                    return;

                Program.SetConfig(Program.CONFIG_IPADDRESS, tstxtIpAddress.Text);
                Program.SetConfig(Program.CONFIG_PORT, tstxtPort.Text);

                m_tTrace = new System.Threading.Thread(new System.Threading.ThreadStart(ReadTrace));
                if (m_tTrace == null)
                    return;

                m_tTrace.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Program.APP_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsbtnDisconnect_Click(object sender, EventArgs e)
        {
            if (m_objTcpClient != null && m_objTcpClient.Connected)
                m_objTcpClient.Close();

            m_objTcpClient = null;
        }

        private void tsbtnNew_Click(object sender, EventArgs e)
        {
            txtMsg.Clear();
        }

        private void tsbtnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog objSaveFileDialog = new SaveFileDialog();
            objSaveFileDialog.Filter = "Text Files | *.txt | All Files | *.*";
            objSaveFileDialog.AddExtension = true;
            objSaveFileDialog.ShowDialog();

            if (objSaveFileDialog.FileName.Equals(string.Empty))
                return;

            System.IO.StreamWriter sw = new System.IO.StreamWriter(objSaveFileDialog.FileName);
            if (sw == null)
                return;

            sw.Write(txtMsg.Text);
            sw.Close();
        }

        private void tsbtnCopy_Click(object sender, EventArgs e)
        {
            if (txtMsg.Text.Equals(string.Empty))
                return;

            Clipboard.SetText(txtMsg.Text);
        }

        private void tsbtnAutoScroll_Click(object sender, EventArgs e)
        {
            tsbtnAutoScroll.Checked = !tsbtnAutoScroll.Checked;
        }

        private void tsbtnWrapText_Click(object sender, EventArgs e)
        {
            tsbtnWrapText.Checked = !tsbtnWrapText.Checked;
            txtMsg.WordWrap = tsbtnWrapText.Checked;
        }

        private void tmrTbActivation_Tick(object sender, EventArgs e)
        {
            tsbtnNew.Enabled = !txtMsg.Text.Equals(string.Empty);
            tsbtnCopy.Enabled = !txtMsg.Text.Equals(string.Empty);
            tsbtnSave.Enabled = !txtMsg.Text.Equals(string.Empty);

            if (m_objTcpClient == null)
            {
                tsbtnConnect.Enabled = true;
                tsbtnDisconnect.Enabled = false;
            }
            else
            {
                tsbtnConnect.Enabled = !m_objTcpClient.Connected;
                tsbtnDisconnect.Enabled = m_objTcpClient.Connected;
            }
        }

        private void tsbtnClose_Click(object sender, EventArgs e)
        {
            tsbtnDisconnect_Click(null, null);
            this.Close();
        }
    }
}